package petstore.web.servlet.signup;

import petstore.persistence.user.User;
import petstore.persistence.user.UserDAOImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class signupServlet extends HttpServlet {
    private String signUpCode;//用于从session获取生成的验证码
    private String username;//提交的用户名
    private String password;//提交的密码
    private String repassword;//再次提交的密码
    private String code;//提交的验证码

    private String signupMsg;//反馈信息

    User user;//用户类

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取提交的信息
        this.username=req.getParameter("username");
        this.password=req.getParameter("password");
        this.repassword=req.getParameter("repassword");
        this.code=req.getParameter("code");
        //从session中获取生成的验证码
        HttpSession session= req.getSession();
        this.signUpCode=(String) session.getAttribute("validateCode");

        //判断是否合法
        if(!isValid()){
            req.setAttribute("signupMsg",signupMsg);
            req.getRequestDispatcher("signup").forward(req,resp);
        }else{
            //如果合法，创建用户
            UserDAOImpl userDAO=new UserDAOImpl();
            System.out.println("IntoCreate");
            user=new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setKey_cat(5);
            user.setKey_dog(5);
            user.setKey_bugcat(5);
            user.setKey_pokemon(5);
            user.setKey_bird(5);
            userDAO.InsertUser(user);
            req.setAttribute("signupMsg","注册成功");
            req.getRequestDispatcher("login").forward(req,resp);
        }


    }

    //判断信息是否合法
    private boolean isValid(){
        if(!this.code.equalsIgnoreCase(signUpCode))
        {
            System.out.println(signUpCode);
            System.out.println(this.code);
            this.signupMsg="验证码不正确!";
            return false;
        }
        return true;
    }
}
